package com.douhuayuedu.douhua.wxapi

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.widget.Toast
import com.alibaba.fastjson.JSONObject
import com.eightbitlab.rxbus.Bus
import com.taptech.doufu.R
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.taptech.doufu.listener.HttpResponseListener
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.taptech.doufu.util.TTLog
import com.taptech.doufu.services.personalcenter.WeChatService
import com.taptech.doufu.weex.http.TFHttpResponse
import com.taptech.doufu.weex.http.TFHttpError
import com.taptech.doufu.util.UIUtil
import com.taptech.doufu.services.HomeMainServices
import com.taptech.doufu.ui.view.SharePicPopupWindow
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.taptech.doufu.ui.activity.BrowseActivity
import com.taptech.doufu.services.UGCMainService
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.taptech.doufu.net.httputils.HttpResponseObject
import com.taptech.doufu.bean.CommentDataBean
import com.taptech.doufu.util.DiaobaoUtil
import com.taptech.doufu.bean.ShareBeansInfo
import com.taptech.doufu.constant.Constant
import com.taptech.doufu.event.LoginStateEvent
import com.taptech.doufu.ext.appToast
import com.taptech.doufu.services.personalcenter.AccountService
import com.taptech.doufu.ui.activity.me.PhoneBindActivity
import com.taptech.doufu.util.NotifyUtil
import com.taptech.doufu.weex.notification.QLXNotificationCenter
import org.json.JSONException
import rx.Observable
import java.util.concurrent.TimeUnit

class WXEntryActivity : DiaobaoBaseActivity(), IWXAPIEventHandler, HttpResponseListener {
    private val TAG = "WXEntryActivity"

    // wx
    private var wxAPI: IWXAPI? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        registerShareServices()
    }

    private fun registerShareServices() {

        // wx
        wxAPI = WXAPIFactory.createWXAPI( /*getThisActivity()*/this, Constant.WX_APP_ID, true)
        wxAPI?.registerApp(Constant.WX_APP_ID)
        wxAPI?.handleIntent(intent, this)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        wxAPI!!.handleIntent(intent, this)
    }

    override fun onResp(resp: BaseResp) {
        var result = 0
        if (resp.type == ConstantsAPI.COMMAND_SENDAUTH) { //登录授权
            if (resp.errCode == BaseResp.ErrCode.ERR_OK) { //用户同意
                val code = (resp as SendAuth.Resp).code
                TTLog.d(TAG, code)
                if (pageType == PAGE_TYPE_WEEX_WECHAT) {  //weex页面
                    if (opType == OP_TYPE_LOGIN_WECHAT) { //登录
                        NotifyUtil.thirdLoginWeChatLogin(code, "授权成功，正在获取登录信息")
                    } else { //绑定
                    }
                } else { //原生
                    val instance = WeChatService.getInstance(this@WXEntryActivity)
                    instance.wxcodelogin(code) { json: JSONObject, error: TFHttpError? ->
                        try {
                            var status = json.getIntValue("status")
                            if (status == 0) {
                                var data = json.getJSONObject("data")
                                AccountService.setAccountData(data.toJSONString(),null)
                                QLXNotificationCenter.getInstance()
                                    .postNotify("kTFUserDidLoginCompleteNotification", null)
                                Bus.send(LoginStateEvent(true)) //相关页面监听到后刷新页面
                                var mobile = AccountService.getInstance().baseAccount.mobile;
                                if (mobile == null || mobile.isEmpty()) {
                                    //手机号为空去绑定手机号
                                    PhoneBindActivity.startActivity(this)
                                }
                            } else {
                                //失败，提示
                                var message = json.getString("user_msg")
                                if (message != null) {
                                    appToast(message)
                                } else {
                                    appToast("登录失败")
                                }
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                            appToast("登录失败")
                        }
                    }
                }
            } else {
                if (pageType == PAGE_TYPE_WEEX_WECHAT) {  //weex页面
                    if (opType == OP_TYPE_LOGIN_WECHAT) { //登录
                        NotifyUtil.thirdLoginWeChatLogin("", "授权失败，请重新登录")
                    } else { //绑定
                    }
                } else { //原生
                    UIUtil.toastMessage(this, "授权失败，请重新登录")
                }
                UIUtil.dismissDialog()
            }
        } else {
            //分享调用处理
            when (resp.errCode) {
                BaseResp.ErrCode.ERR_OK -> if (shareInfo != null && shareInfo!!.isForWeex) {
                    NotifyUtil.shareNotify("分享成功")
                } else {
                    if (shareInfo != null && shareInfo!!.getId() != null) {
                        var objectType = shareInfo!!.object_type
                        if (shareInfo!!.shareData != null && !TextUtils.isEmpty(
                                shareInfo!!.shareData.object_type
                            )
                        ) {
                            objectType = shareInfo!!.shareData.object_type
                        }
                        HomeMainServices.getInstance().getShareUrlRequest(
                            shareInfo!!.getId(),
                            objectType, null, shareInfo!!.shareUrl
                        )
                        if (SharePicPopupWindow.wxShareType == SendMessageToWX.Req.WXSceneSession) { //haoyou
                            BrowseActivity.sendCallbackTojs("wechat_friends")
                            UGCMainService.getInstance().uploadShareScore(
                                shareInfo!!.getId(),
                                102.toString(),
                                objectType,
                                this@WXEntryActivity
                            )
                        } else if (SharePicPopupWindow.wxShareType == SendMessageToWX.Req.WXSceneTimeline) { //pegnyouquan
                            BrowseActivity.sendCallbackTojs("wechat_pengyouquan")
                            UGCMainService.getInstance().uploadShareScore(
                                shareInfo!!.getId(),
                                103.toString(),
                                objectType,
                                this@WXEntryActivity
                            )
                        }
                        shareInfo = ShareBeansInfo()
                    } else {
                        if (SharePicPopupWindow.wxShareType == SendMessageToWX.Req.WXSceneSession) { //haoyou
                            BrowseActivity.sendCallbackTojs("wechat_friends")
                            UGCMainService.getInstance()
                                .uploadShareScore("3", 102.toString(), "22", this@WXEntryActivity)
                        } else if (SharePicPopupWindow.wxShareType == SendMessageToWX.Req.WXSceneTimeline) { //pegnyouquan
                            BrowseActivity.sendCallbackTojs("wechat_pengyouquan")
                            UGCMainService.getInstance()
                                .uploadShareScore("3", 103.toString(), "22", this@WXEntryActivity)
                        }
                    }
                }
                BaseResp.ErrCode.ERR_USER_CANCEL -> {
                    result = R.string.errcode_cancel
                    if (shareInfo != null && shareInfo!!.isForWeex) {
                        NotifyUtil.shareNotify(getString(result))
                    } else {
                        Toast.makeText(this, result, Toast.LENGTH_SHORT).show()
                    }
                }
                BaseResp.ErrCode.ERR_AUTH_DENIED -> {
                    result = R.string.errcode_deny
                    if (shareInfo != null && shareInfo!!.isForWeex) {
                        NotifyUtil.shareNotify(getString(result))
                    } else {
                        Toast.makeText(this, result, Toast.LENGTH_SHORT).show()
                    }
                }
                else -> {
                    result = R.string.errcode_unknown
                    if (shareInfo != null && shareInfo!!.isForWeex) {
                        NotifyUtil.shareNotify(getString(result))
                    } else {
                        Toast.makeText(this, result, Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
        finish()
    }

    override fun onReq(req: BaseReq) {}
    override fun handleResponse(handleType: Int, response: HttpResponseObject) {
        if (handleType == UGCMainService.HANDLE_TYPE_LOAD_SHARE_SCORE) {
            try {
                if (response.status == 0) {
                    UIUtil.dismissDialog()
                    val scrore = CommentDataBean()
                    scrore.setJson((response.data as org.json.JSONObject).getJSONObject("score_result"))
                    val commentScore = Integer.valueOf(scrore.score)
                    if (commentScore != 0) {
                        UIUtil.toastMessage(this@WXEntryActivity, "分享成“攻” +5豆子")
                    } else {
                        UIUtil.toastMessage(
                            this@WXEntryActivity,
                            "分享成“攻”" + Constant.REPLY_TODAY_FULL
                        )
                    }
                } else {
                    UIUtil.toastMessage(this@WXEntryActivity, DiaobaoUtil.getErrorTips(response))
                }
                finish()
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        } else if (handleType == WeChatService.HANDLE_WECHAT_BIND_REGIST) {
            UIUtil.toastMessage(this@WXEntryActivity, "登录回调")
        }
    }

    companion object {
        const val OP_TYPE_LOGIN_WECHAT = 0 //登录
        const val OP_TYPE_BIND_WECHAT = 1 //绑定
        const val PAGE_TYPE_NATIVE_WECHAT = 0 //原生
        const val PAGE_TYPE_WEEX_WECHAT = 1 //weex
        var opType = OP_TYPE_LOGIN_WECHAT //操作类型
        var pageType = PAGE_TYPE_NATIVE_WECHAT //页面类型
        var shareInfo: ShareBeansInfo = ShareBeansInfo()
    }
}